# -*- coding: utf-8 -*-

import sys
import logging
import json
from logging.handlers import RotatingFileHandler

from flask import Flask
from flask import request

path = sys.path[0].split('/')
path = "/".join(path[0:-1])
sys.path.append(path)

from train import train as model_train
from predict import predict as model_predict
app = Flask(__name__)

@app.route('/train', methods=['POST'])
def train():
    data = request.data.decode("ascii")
    app.logger.info("train request : {0}".format(data))
    data = json.loads(data)
    db_name = data['db_name']
    job_id = data["job_id"]
    model_train(app, db_name, job_id)
    return json.dumps({"ret": "ok"})


@app.route('/predict', methods=['POST'])
def predict():
    data = json.loads(request.data)
    db_name = data['db_name']
    collect_name = data["collect_name"]
    result = model_predict(app, db_name, collect_name)
    return json.dumps({"ret": "ok", "predict": result})

if __name__ == '__main__':
    logger_handler = RotatingFileHandler("./logs/text_classify_server.log", maxBytes=1*1024*1024, backupCount=5)
    logging_format = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
    logger_handler.setFormatter(logging_format)
    app.logger.addHandler(logger_handler)
    app.run(host="0.0.0.0", port=10023, debug=True)